package com.jerry.usbserial.util.task.usb

import android.content.Context
import com.jerry.usbserial.activity.UsbService
import com.jerry.usbserial.util.*
import java.util.*
import kotlin.concurrent.timerTask

abstract class UsbTask(val mContext: Context, private val mUsbService: UsbService) {
    protected var mStep = 0
    private var mIsClosed = false
    private var mTimer: Timer? = null
    private var mRetry = 0

    protected fun write(data: ByteArray, retry: Boolean = true) {
        if (mIsClosed) return
        try {
            mUsbService.write(data)
            if (retry) {
                if (mRetry < 10) {
                    mRetry++
                    mTimer = Timer().apply {
                        schedule(timerTask {
                            postMsg("设备响应超时...重试")
                            write(data, retry)
                        }, 5000)
                    }
                } else {
                    postError("设备无响应,升级任务失败!")
                }
            }
        } catch (e: Exception) {
            postError("数据发送失败,请检查连接!")
        }
    }


    abstract fun start()

    fun close() {
        mIsClosed = true
    }

    fun disconnect() {
        if (interruptTask()) {
            close()
            mTimer?.cancel()
            mTimer = null
            postError("设备连接已断开,任务停止!")
        }
    }

    open fun interruptTask(): Boolean = true

    open fun onResult(data: ByteArray) {
        mTimer?.cancel()
        mTimer = null
        mRetry = 0
    }
}